<?php

require_once 'Zend/Registry.php';

class St_Registry extends Zend_Registry {
    /*
     * get database instance
     * @return instance of Vi_Db
     */

    public static function getDB() {
        return St_Registry::get('db');
    }

    /*
     * get instance of StLayout
     * @return layout instance
     */

    public static function getLayout() {
        return Zend_Layout::getMvcInstance();
    }

    /*
     * get view instance
     * @return instance of view
     */

    public static function getView() {
        return Zend_Layout::getMvcInstance()->getView();
    }

    /*
     * get template engine of view 
     * @return a template engine, the default is smarty 
     */

    public static function getTemplateEngine() {
        return St_Registry::getView()->getEngine();
    }

    public static function getTranslator() {
        return St_Registry::get("translator");
    }

    /*
     * get base url 
     * @return string of base url
     */

    public static function getBaseUrl($extend = '') {
        return St_Registry::get('BASE_URL') . $extend;
    }

    /*
     * get application name
     * @return string of application
     */

    public static function getAppName() {
        return St_Registry::get('APP_NAME');
    }

    /*
     * get application url
     * @return string of application url
     */

    public static function getAppBaseUrl() {
        return St_Registry::get('APP_BASE_URL');
    }

    public static function getHelperUrl() {
        $moduleName = St_Registry::getModuleName();
        return St_Registry::get('BASE_URL') . "modules/{$moduleName}/views/helpers/";
    }

    /*
     * get config
     * 
     * $name string
     * @return array config
     */

    public static function getConfig($name = false) {
        if (false === $name) {
            return St_Registry::get('config');
        } else {
            $config = St_Registry::get('config');
            return $config[$name];
        }
    }

    /*
     * get request object
     * @return Zend_Controller_Request_Abstract
     */

    public static function getRequest() {
        return Zend_Controller_Front::getInstance()->getRequest();
    }

    /**
     * get response object
     * @return Zend_Controller_Response_Abstract
     */
    public static function getResponse() {
        return Zend_Controller_Front::getInstance()->getResponse();
    }

    /**
     * get router object
     * @return Zend_Controller_Router_Abstract
     */
    public static function getRouter() {
        return Zend_Controller_Front::getInstance()->getRouter();
    }

    /**
     * get module name
     * @return string current module name
     */
    public static function getModuleName() {
        return Zend_Controller_Front::getInstance()->getRequest()->getModuleName();
    }

    public static function getModuleKey() {
        return Zend_Controller_Front::getInstance()->getRequest()->getModuleKey();
    }

    public static function getControllerName() {
        return Zend_Controller_Front::getInstance()->getRequest()->getControllerName();
    }

    public static function getControllerKey() {
        return Zend_Controller_Front::getInstance()->getRequest()->getControllerKey();
    }

    public static function getActionName() {
        return Zend_Controller_Front::getInstance()->getRequest()->getActionName();
    }

    public static function getActionKey() {
        return Zend_Controller_Front::getInstance()->getRequest()->getActionKey();
    }

    /**
     * get database prefix
     * @return string prefix for database
     */
    public static function getDBPrefix() {
        $config = St_Registry::getConfig();
        return $config['database']['params']['prefix'];
    }

    public static function getSession() {
        return St_Registry::get('session');
    }

    public static function getAcl() {
        if (St_Registry::isRegistered('acl')) {
            return St_Registry::get('acl');
        } else {
            return null;
        }
    }

    public static function getAclFront() {
        if (St_Registry::isRegistered('aclFront')) {
            return St_Registry::get('aclFront');
        } else {
            return null;
        }
    }

    public static function getAclAdmin() {
        if (St_Registry::isRegistered('aclAdmin')) {
            return St_Registry::get('aclAdmin');
        } else {
            return null;
        }
    }

    public static function getAuth() {
        return St_Registry::get('auth');
    }

    public static function highlight($needle, $haystack) {
        $ind = stripos($haystack, $needle);
        $len = strlen($needle);
        if ($ind !== false) {
            return substr($haystack, 0, $ind) . "<b>" . substr($haystack, $ind, $len) . "</b>" .
                    St_Registry::highlight($needle, substr($haystack, $ind + $len));
        } else
            return $haystack;
    }

    public static function sendMessage($message) {
        echo "<script type='text/javascript'>"
        . 'jQuery(document).ready(function(){'
        . "myAds.sendMessage('$message');"
        . '});'
        . "</script>"
        ;
    }

    public static function generateRandomNumber($length = 12) {

        $chars = '0123456789987654321025896314706547893210';

        $number = '';
        for ($i = 0; $i < $length; $i++) {
            $number .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $number;
    }

    public static function generateRandomPassword($length = 12, $special_chars = true, $extra_special_chars = false) {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        if ($special_chars)
            $chars .= '!@#$%^&*()';
        if ($extra_special_chars)
            $chars .= '-_ []{}<>~`+=,.;:/?|';

        $password = '';
        for ($i = 0; $i < $length; $i++) {
            $password .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $password;
    }

    public static function saveOption($optionName, $optonValue) {
        Zend_Loader::loadClass("St_Option");
        $optionObj = new St_Option();
        $id = $optionObj->isExist($optionName);
        $data = array(
            'OptionName' => $optionName,
            'OptionValue' => St_Registry::maybeSerialize($optonValue)
        );
        if ($id) {
            return $optionObj->update($data, "OptionID = '$id'");
        } else {
            return $optionObj->insert($data);
        }
    }

    public static function getOption($optionName) {
        Zend_Loader::loadClass("St_Option");
        $optionObj = new St_Option();
        return St_Registry::maybeUnserialize($optionObj->getOption($optionName));
    }

    public static function maybeSerialize($data) {
        if (is_array($data) || is_object($data))
            return serialize($data);

        if (St_Registry::isSerialized($data))
            return serialize($data);

        return $data;
    }

    public static function maybeUnserialize($original) {
        if (St_Registry::isSerialized($original)) // don't attempt to unserialize data that wasn't serialized going in
            return @unserialize($original);
        return $original;
    }

    public static function isSerialized($data) {
        // if it isn't a string, it isn't serialized
        if (!is_string($data))
            return false;
        $data = trim($data);
        if ('N;' == $data)
            return true;
        $length = strlen($data);
        if ($length < 4)
            return false;
        if (':' !== $data[1])
            return false;
        $lastc = $data[$length - 1];
        if (';' !== $lastc && '}' !== $lastc)
            return false;
        $token = $data[0];
        switch ($token) {
            case 's' :
                if ('"' !== $data[$length - 2])
                    return false;
            case 'a' :
            case 'O' :
                return (bool) preg_match("/^{$token}:[0-9]+:/s", $data);
            case 'b' :
            case 'i' :
            case 'd' :
                return (bool) preg_match("/^{$token}:[0-9.E-]+;\$/", $data);
        }
        return false;
    }

    public static function limitWord($mycontent, $excerpt = false, $more_link_text = null, $limit = 10) {
        $mycontent = strip_tags($mycontent);
        $teaser = false;
        if (null === $more_link_text)
            $more_link_text = '...';
//            $more_link_text = __('(more...)', $this->config['plugin_name']);

        if ($excerpt) {
            $words = explode(' ', $mycontent, $limit + 1);

            if (count($words) > $limit) :
                array_pop($words);
                array_push($words, ' ...');
                $mycontent = implode(' ', $words);
            endif;

            $mycontent = str_replace(']]>', ']]&gt;', $mycontent);
        }
        return $mycontent;
    }

    public static function Redirect($location) {
        return "<script type='text/javascript'>"
                . "window.location = '$location';"
                . "</script>"
        ;
    }
    
    public static function sendAWSEmail($data) {
        $data['token'] = "8asd6f8a7ds6fa6a8sdf";
        $apiURL = "http://test.slopetracker.no/phuc/sesservice/service.php?rnd=" . time();
        $ch = curl_init($apiURL);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $returndata = curl_exec($ch);
        return $returndata;
    }
    
    public static function getCurrentUser() {
        if (St_Registry::isRegistered('user_data')) {
            return St_Registry::get('user_data');
        }
        $auth = St_Registry::get('auth');
        if (!$auth->isLogin()) {
            return false;
        } else {
            $username = $auth->getUsername();
            $db = St_Registry::getDB();

            $selectUser = $db->select()->from('user')->where("email = '{$username}'");
            $select = $db->select()
                    ->from(array('u' => $selectUser))
                    ->joinLeft(array('g' => 'group'), 'u.GroupID = g.GroupID', array('GroupName' => 'GroupName', 'GroupMenu' => 'GroupMenu'));
            $user = $db->fetchRow($select);
            St_Registry::set('user_data', $user);
            return $user;
        }
    }

}